Tutorial 8: Trust region policy optimization (TRPO)¶
Tutorials for course ECE1508 Reinforcement Learning at the University of Toronto.
Author: Yicheng (Eason) Qu
Email: eason.qu@mail.utoronto.ca
The schedule of this tutorial¶
- Review of vanilla policy gradient method
- Introduce the trust region to improve the stability
- Details of TRPO
- Implementations
Motivation & Intuition¶
Why TRPO?¶
Reinforcement learning using vanilla policy gradients or actor-critic methods can sometimes fail due to unstable updates:
- Policy parameters are updated using gradient ascent on expected reward.
- Large gradient steps can cause the new policy to perform worse than the old policy.
- Variance in gradient estimates makes this problem worse.
This phenomenon is often called policy collapse.
The Idea of Trust Region¶
TRPO introduces the concept of a trust region:
- Constrain policy updates to stay close to the current policy.
- "Close" is measured using KL divergence between old and new policy distributions.
- Only allow updates that stay within a safe step, preventing catastrophic drops in performance.
Visual Analogy¶
We can visualize the policy update in parameter space. The new policy should stay within a “KL circle” around the old policy.
import matplotlib.pyplot as plt
import numpy as np
# Old policy location
old_policy = np.array([0, 0])
# Example gradient step (overshoot)
grad_step = np.array([1.5, 1.0])
# Trust region radius
radius = 1.0
fig, ax = plt.subplots(figsize=(6,6))
# KL trust region circle
circle = plt.Circle(old_policy, radius, color='blue', alpha=0.2, label='KL Trust Region')
ax.add_patch(circle)
# Plot old policy
ax.plot(old_policy[0], old_policy[1], 'o', color='green', label='Old Policy', markersize=10)
# Plot new policy (overshoot)
ax.plot(old_policy[0]+grad_step[0], old_policy[1]+grad_step[1], 'o', color='red', label='Proposed Update')
# Plot arrow
ax.arrow(old_policy[0], old_policy[1], grad_step[0]-0.1, grad_step[1]-0.1, head_width=0.1, head_length=0.15, fc='red', ec='red')
ax.set_xlim(-0.5, 2.5)
ax.set_ylim(-0.5, 2.5)
ax.set_xlabel('Policy Parameter 1')
ax.set_ylabel('Policy Parameter 2')
ax.set_title('TRPO Trust Region Illustration')
ax.legend()
ax.set_aspect('equal')
plt.show()
Visual Analogy with Intuition¶
The figure above shows policy updates in a 2D parameter space:
- Green dot: represents the current (old) policy.
- Red dot: represents the proposed policy update from a vanilla policy gradient step.
- Red arrow: direction and size of the unconstrained gradient step.
- Blue circle: the trust region, defined by a maximum allowed KL divergence $\delta$.
Intuition¶
Vanilla policy gradient (red dot & arrow)
- Takes a step in the direction of the gradient.
- If the step is too large, the new policy may move outside the safe region, causing performance to drop.
- In other words, the policy “overshoots” and can behave poorly.
TRPO update (within blue circle)
- TRPO constrains the update so that the new policy stays inside the KL trust region.
- This ensures that the new policy remains close to the old policy, providing stable improvement.
- Essentially, TRPO answers: “How far can we move this policy safely without hurting performance?”
The figure illustrates why unconstrained updates can be dangerous and how TRPO stabilizes learning.
Recap of Vanilla Policy Gradient & Actor-Critic¶
Before we dive into TRPO, let's quickly refresh the core ideas behind policy gradient methods and actor-critic.
1. Policy Gradient Methods¶
Goal: Directly optimize the policy network $\pi_\theta(a|s)$ to maximize expected reward:
$$ \large J(\theta) = \mathbb{E}_{\tau \sim \pi_\theta} \left[ R(\tau) \right] $$
where $R(\tau) = \sum_{t=0}^T r_t$ is the return of trajectory $\tau$.
The policy gradient theorem gives:
$$ \large \nabla_\theta J(\theta) = \mathbb{E}_{s_t, a_t \sim \pi_\theta} \Big[ \nabla_\theta \log \pi_\theta(a_t|s_t) \, Q^\pi(s_t, a_t) \Big] $$
- $Q^\pi(s, a)$ = expected return after taking action $a$ in state $s$ under policy $\pi$
- In practice, we often replace $Q^\pi$ with advantage function:
$$ \large A^\pi(s, a) = Q^\pi(s, a) - V^\pi(s) $$
Using the advantage reduces variance of the gradient estimate.
2. Actor-Critic¶
- Actor: The policy network $\pi_\theta(a|s)$
- Critic: Estimates the value function $V^\pi(s)$ (used for advantage computation)
Gradient update (actor):
$$ \large \nabla_\theta J(\theta) \approx \mathbb{E}\big[\nabla_\theta \log \pi_\theta(a_t|s_t) \, A_t \big] $$
Value update (critic):
$$ \large L(\phi) = \mathbb{E} \big[ (V_\phi(s_t) - R_t)^2 \big] $$
- The critic helps reduce variance without introducing bias.
3. Key Takeaways for TRPO¶
- TRPO still uses the actor-critic framework:
- Advantage estimates $A_t$ are computed with a critic
- Actor policy is updated probabilistically
- Difference: TRPO constrains the actor update to stay close to the old policy via KL divergence.
Trust Region Policy Optimization (TRPO)¶
TRPO is a policy-gradient method designed to improve the stability of policy updates in reinforcement learning.
1. TRPO Optimization Problem¶
TRPO optimizes the surrogate objective subject to a KL divergence constraint:
$$ \large \displaystyle \max_\theta \ \hat{\mathbb{E}}_t \Bigg[ \frac{\pi_\theta(a_t|s_t)}{\pi_{\theta_{\text{old}}}(a_t|s_t)} \, A_t \Bigg] $$
subject to
$$ \large \displaystyle \hat{\mathbb{E}}_t \Big[ D_{\mathrm{KL}}\big(\pi_{\theta_{\text{old}}}(\cdot|s_t) \,\|\, \pi_\theta(\cdot|s_t)\big) \Big] \le \delta $$
Where:
- $\pi_\theta(a|s)$: the current policy with parameters $\theta$
- $\pi_{\theta_{\text{old}}}(a|s)$: the old policy (before the update)
- $A_t$: advantage estimate at time $t$
- $\delta$: maximum allowed KL divergence (trust region size)
- $\hat{\mathbb{E}}_t$: empirical expectation over collected trajectories
1.1 Surrogate Objective¶
Can we keep the vanilla PG objective and add a KL constraint? Yes. This can give a useful update. To understand why TRPO changes the objective, we must distinguish computing a gradient at the old policy from evaluating a candidate policy after a finite change.
What Does the PG Objective Tell Us?¶
Using a batch collected under the old policy, a common PG objective is:
$$\large L_{\mathrm{PG}}(\theta) = \hat{\mathbb{E}}_t \big[\log \pi_\theta(a_t|s_t)\,A_t\big]. $$
Here, the batch and $A_t$ are held fixed. Differentiating this expression at $\theta_{\text{old}}$ gives the usual policy-gradient estimate. However, its value is not the expected return: an increase in advantage-weighted log probabilities need not measure an increase in reward.
What Should the New Objective Measure?¶
At a fixed state $s$, we would like the candidate policy to choose actions with a larger expected old-policy advantage:
$$\large \sum_a \pi_\theta(a|s)\,A^{\pi_{\text{old}}}(s,a). $$
The actions in our data were sampled from $\pi_{\text{old}}$, so we rewrite this quantity as:
$$\large \begin{aligned} \sum_a \pi_\theta(a|s)\,A^{\pi_{\text{old}}}(s,a) &= \sum_a \pi_{\text{old}}(a|s) \frac{\pi_\theta(a|s)}{\pi_{\text{old}}(a|s)} A^{\pi_{\text{old}}}(s,a)\\ &= \mathbb{E}_{a\sim\pi_{\text{old}}(\cdot|s)} \left[\frac{\pi_\theta(a|s)}{\pi_{\text{old}}(a|s)} A^{\pi_{\text{old}}}(s,a)\right]. \end{aligned} $$
Assuming the old policy assigns positive probability to the candidate's actions, this identity gives TRPO's sampled objective:
$$\large L_{\mathrm{TRPO}}(\theta) = \hat{\mathbb{E}}_t \left[ \frac{\pi_\theta(a_t|s_t)} {\pi_{\theta_{\text{old}}}(a_t|s_t)}\,A_t \right]. $$
The ratio appears because we want an expectation under the candidate's action probabilities, using actions sampled from the old policy. The log objective does not have this interpretation. In a multi-step problem, TRPO still uses the old policy's state visitation distribution, so this remains a surrogate for return improvement.
Takeaway: PG with KL is a valid alternative and agrees with TRPO to first order. TRPO chooses the ratio objective because it measures expected old-policy advantage under the candidate's action probabilities and is the surrogate used in its policy-improvement bound. The KL constraint helps control the remaining approximation error; practical TRPO still has no guarantee that every sampled update improves true return.
1.2 KL Constraint¶
For a fixed state $s$, the KL divergence between the old and new action distributions is:
$$ \large D_{\mathrm{KL}}\big(\pi_{\theta_{\text{old}}}(\cdot|s) \,\|\, \pi_\theta(\cdot|s)\big) = \sum_a \pi_{\theta_{\text{old}}}(a|s) \log \frac{\pi_{\theta_{\text{old}}}(a|s)}{\pi_\theta(a|s)}. $$
KL divergence is nonnegative and equals $0$ when the distributions are identical. For continuous actions, the sum becomes an integral.
In TRPO, we constrain its average over the sampled states:
$$\large \hat{\mathbb{E}}_t \Big[ D_{\mathrm{KL}}\big(\pi_{\theta_{\text{old}}}(\cdot|s_t) \,\|\, \pi_\theta(\cdot|s_t)\big) \Big] \le \delta $$
Why Use KL Divergence?¶
- Measure behavior, not just network weights: A small parameter change can cause a large change in action probabilities. KL directly compares what the two policies would do in the same state.
- Compare the whole action distribution: With two actions, changing probabilities from $(0.5, 0.5)$ to $(0.52, 0.48)$ gives a small KL; changing them to $(0.99, 0.01)$ gives a much larger KL. The latter makes behavior nearly deterministic and may discard useful actions too quickly.
- Connect to the improvement theory: TRPO's theoretical bound controls the error in the surrogate using a worst-case KL over states. The sampled average above is a practical approximation, so a small average does not ensure a small change at every state.
- Support efficient optimization: Near the old policy, KL has a quadratic approximation involving the Fisher information matrix, which TRPO uses to compute its update.
Takeaway: KL provides a meaningful budget for changing the policy's action probabilities. A smaller $\delta$ encourages more conservative updates.
Reference: Schulman et al. (2015), Trust Region Policy Optimization, Sections 3-6.
2.Key Steps in TRPO¶
TRPO modifies the standard policy gradient update by constraining it within a trust region. The conceptual workflow is:
2.1. Collect trajectories using the current policy $\pi_{\theta_{\text{old}}}$¶
- Sample states, actions, and rewards by rolling out the old policy.
- Unlike vanilla PG, TRPO explicitly keeps a copy of the old policy for computing the importance sampling ratio and KL divergence.
2.2. Compute advantages $A_t$¶
2.3. Linearize the surrogate objective (first-order approximation)¶
- Let $\theta_\text{old}$ denote the current policy parameters, and consider a small update $\theta - \theta_\text{old}$.
- Linearize the surrogate objective around $\theta_\text{old}$:
$$ \large L(\theta) \approx L(\theta_\text{old}) + g^\top (\theta - \theta_\text{old}) $$
where $g = \nabla_\theta L(\theta)\big|_{\theta_\text{old}}$ is the gradient of the surrogate.
- This gives a first-order approximation of expected policy improvement, similar to vanilla PG but expressed relative to the old policy.
2.4. Quadratically approximate the KL constraint (second-order)¶
- TRPO constrains updates by the KL divergence between old and new policies:
$$\large D_\mathrm{KL}(\pi_{\theta_\text{old}} \,\|\, \pi_\theta) = \hat{\mathbb{E}}_t \Big[ \sum_a \pi_{\theta_\text{old}}(a|s_t) \log \frac{\pi_{\theta_\text{old}}(a|s_t)}{\pi_\theta(a|s_t)} \Big] $$
- Around $\theta_\text{old}$, the KL divergence can be approximated quadratically:
$$\large D_\mathrm{KL}(\pi_{\theta_\text{old}} \,\|\, \pi_\theta) \approx \frac{1}{2} (\theta - \theta_\text{old})^\top F (\theta - \theta_\text{old}) $$
Fisher Information Matrix (F)¶
- Defined as:
$$\large F = \hat{\mathbb{E}}_{s \sim \rho_{\pi_\text{old}},\, a \sim \pi_{\theta_\text{old}}} \Big[ \nabla_\theta \log \pi_\theta(a|s) \, \nabla_\theta \log \pi_\theta(a|s)^\top \Big] \Big|_{\theta_\text{old}} $$
- Captures the local curvature of the policy distribution.
- Acts as a metric tensor, measuring distances in policy space in terms of KL divergence rather than parameter space.
- Estimated empirically by sampling $(s_t, a_t)$ from trajectories collected under $\pi_{\theta_\text{old}}$.
2.5. Solve the constrained optimization¶
We want to maximize the linearized surrogate objective subject to the quadratic KL constraint:
$$\large \max_\theta \ g^\top (\theta - \theta_\text{old}) \quad \text{s.t.} \quad \frac{1}{2} (\theta - \theta_\text{old})^\top F (\theta - \theta_\text{old}) \le \delta $$
2.5.1 Deriving the natural gradient¶
- This is a constrained quadratic optimization problem.
- Using the method of Lagrange multipliers, we define the Lagrangian:
$$\large \mathcal{L}(\theta, \lambda) = g^\top (\theta - \theta_\text{old}) - \lambda \Big( \frac{1}{2} (\theta - \theta_\text{old})^\top F (\theta - \theta_\text{old}) - \delta \Big) $$
- Setting the derivative with respect to $\theta$ to zero:
$$\large \nabla_\theta \mathcal{L} = g - \lambda F (\theta - \theta_\text{old}) = 0 \quad \Rightarrow \quad \theta - \theta_\text{old} = \frac{1}{\lambda} F^{-1} g $$
- The step direction is the natural gradient:
$$\large \theta^* - \theta_\text{old} \propto F^{-1} g $$
- The scalar $\frac{1}{\lambda}$ is chosen to satisfy the KL constraint exactly.
Intuition:
- Instead of stepping along $g$ in parameter space (vanilla PG), TRPO steps along $F^{-1} g$, the direction that maximizes expected improvement per unit of KL divergence.
2.5.2 Computing $F^{-1} g$ with conjugate gradient¶
- Directly computing $F^{-1}$ is computationally infeasible for large networks. Matrix inversion is $O(n^3)$.
- Instead, TRPO uses the conjugate gradient (CG) algorithm, an iterative method for solving linear systems:
$$\large F x = g \quad \Rightarrow \quad x = F^{-1} g $$
- CG requires only matrix-vector products $Fv$, which can be computed efficiently from sampled trajectories, without forming $F$ explicitly.
Why conjugate gradient works for TRPO:
- $F$ is symmetric and positive semi-definite (as a Fisher matrix), which is exactly what CG requires.
- Only a few CG iterations are usually sufficient to get a good approximation.
- This makes TRPO scalable to large neural networks while preserving the natural gradient direction.
2.5.3 Final update with line search¶
- Once we have the approximate natural gradient $x \approx F^{-1} g$, perform a line search along $x$:
$$\large \theta_\text{new} = \theta_\text{old} + \alpha x $$
- Choose $\alpha \in (0,1]$ to ensure the KL constraint is satisfied:
$$\large D_\mathrm{KL}(\pi_{\theta_\text{old}} \,\|\, \pi_{\theta_\text{old} + \alpha x}) \le \delta $$
- This yields the largest safe policy update along the natural gradient direction.
Import libraries¶
import torch
import torch.nn as nn
from torch.distributions import Normal
import scipy
import torch.autograd as autograd
import torch.optim as optim
import os
import pickle
import gym
import numpy as np
import math
import multiprocessing
import time
import matplotlib.pyplot as plt
Gym has been unmaintained since 2022 and does not support NumPy 2.0 amongst other critical functionality. Please upgrade to Gymnasium, the maintained drop-in replacement of Gym, or contact the authors of your software and request that they upgrade. Users of this version of Gym should be able to simply replace 'import gym' with 'import gymnasium as gym' in the vast majority of cases. See the migration guide at https://gymnasium.farama.org/introduction/migration_guide/ for additional information.
Utilities¶
# Math related utilities
def normal_entropy(std):
var = std.pow(2)
entropy = 0.5 + 0.5 * torch.log(2 * var * math.pi)
return entropy.sum(1, keepdim=True)
def normal_log_density(x, mean, log_std, std):
var = std.pow(2)
log_density = -(x - mean).pow(2) / (2 * var) - 0.5 * math.log(2 * math.pi) - log_std
return log_density.sum(1, keepdim=True)
# Path related utilities
def check_path(path):
if not os.path.exists(path):
print(f"{path} not exist")
os.makedirs(path)
print(f"Create {path} success")
# PyTorch related utilities
tensor = torch.tensor
DoubleTensor = torch.DoubleTensor
FloatTensor = torch.FloatTensor
LongTensor = torch.LongTensor
ByteTensor = torch.ByteTensor
ones = torch.ones
zeros = torch.zeros
def to_device(device, *args):
return [x.to(device) for x in args]
def get_flat_params_from(model):
params = []
for param in model.parameters():
params.append(param.view(-1))
flat_params = torch.cat(params)
return flat_params
def set_flat_params_to(model, flat_params):
prev_ind = 0
for param in model.parameters():
flat_size = int(np.prod(list(param.size())))
param.data.copy_(
flat_params[prev_ind:prev_ind + flat_size].view(param.size()))
prev_ind += flat_size
def get_flat_grad_from(inputs, grad_grad=False):
grads = []
for param in inputs:
if grad_grad:
grads.append(param.grad.grad.view(-1))
else:
if param.grad is None:
grads.append(zeros(param.view(-1).shape))
else:
grads.append(param.grad.view(-1))
flat_grad = torch.cat(grads)
return flat_grad
def compute_flat_grad(output, inputs, filter_input_ids=set(), retain_graph=False, create_graph=False):
if create_graph:
retain_graph = True
inputs = list(inputs)
params = []
for i, param in enumerate(inputs):
if i not in filter_input_ids:
params.append(param)
grads = torch.autograd.grad(output, params, retain_graph=retain_graph, create_graph=create_graph)
j = 0
out_grads = []
for i, param in enumerate(inputs):
if i in filter_input_ids:
out_grads.append(zeros(param.view(-1).shape, device=param.device, dtype=param.dtype))
else:
out_grads.append(grads[j].view(-1))
j += 1
grads = torch.cat(out_grads)
for param in params:
param.grad = None
return grads
# ZFilter related utilities
# from https://github.com/joschu/modular_rl
# http://www.johndcook.com/blog/standard_deviation/
class RunningStat(object):
def __init__(self, shape):
self._n = 0
self._M = np.zeros(shape)
self._S = np.zeros(shape)
def push(self, x):
x = np.asarray(x)
assert x.shape == self._M.shape, "shape mismatch, expected %s, got %s" % (self._M.shape, x.shape)
self._n += 1
if self._n == 1:
self._M[...] = x
else:
oldM = self._M.copy()
self._M[...] = oldM + (x - oldM) / self._n
self._S[...] = self._S + (x - oldM) * (x - self._M)
@property
def n(self):
return self._n
@property
def mean(self):
return self._M
@property
def var(self):
return self._S / (self._n - 1) if self._n > 1 else np.square(self._M)
@property
def std(self):
return np.sqrt(self.var)
@property
def shape(self):
return self._M.shape
class ZFilter:
"""
y = (x-mean)/std
using running estimates of mean,std
"""
def __init__(self, shape, demean=True, destd=True, clip=10.0):
self.demean = demean
self.destd = destd
self.clip = clip
self.rs = RunningStat(shape)
self.fix = False
def __call__(self, x, update=True):
if update and not self.fix:
self.rs.push(x)
if self.demean:
x = x - self.rs.mean
if self.destd:
x = x / (self.rs.std + 1e-8)
if self.clip:
x = np.clip(x, -self.clip, self.clip)
return x
Policy Networks¶
The probablistic mapping of expected action value from given state $ \pi_\theta(a|s) $
# For continuous action space
# Here we assume the distribution is Gaussian
class Policy(nn.Module):
def __init__(self, state_dim, action_dim, hidden_size=(128, 128), activation='tanh', log_std=0):
super().__init__()
self.is_disc_action = False
if activation == 'tanh':
self.activation = torch.tanh
elif activation == 'relu':
self.activation = torch.relu
elif activation == 'sigmoid':
self.activation = torch.sigmoid
self.affine_layers = nn.ModuleList()
last_dim = state_dim
for nh in hidden_size:
self.affine_layers.append(nn.Linear(last_dim, nh))
last_dim = nh
self.action_mean = nn.Linear(last_dim, action_dim)
self.action_mean.weight.data.mul_(0.1)
self.action_mean.bias.data.mul_(0.0)
self.action_log_std = nn.Parameter(torch.ones(1, action_dim) * log_std)
def forward(self, x):
for affine in self.affine_layers:
x = self.activation(affine(x))
action_mean = self.action_mean(x)
action_log_std = self.action_log_std.expand_as(action_mean)
action_std = torch.exp(action_log_std)
return action_mean, action_log_std, action_std
def select_action(self, x):
action_mean, _, action_std = self.forward(x)
action = torch.normal(action_mean, action_std)
return action
# Compute KL Divergence for two network parameters (prev policy net vs curr policy net)
def get_kl(self, x):
mean1, log_std1, std1 = self.forward(x)
mean0 = mean1.detach()
log_std0 = log_std1.detach()
std0 = std1.detach()
kl = log_std1 - log_std0 + (std0.pow(2) + (mean0 - mean1).pow(2)) / (2.0 * std1.pow(2)) - 0.5
return kl.sum(1, keepdim=True)
def get_log_prob(self, x, actions):
action_mean, action_log_std, action_std = self.forward(x)
return normal_log_density(actions, action_mean, action_log_std, action_std)
# Get Fisher Information Matrix
def get_fim(self, x):
mean, _, _ = self.forward(x)
cov_inv = self.action_log_std.exp().pow(-2).squeeze(0).repeat(x.size(0))
param_count = 0
std_index = 0
id = 0
for name, param in self.named_parameters():
if name == "action_log_std":
std_id = id
std_index = param_count
param_count += param.view(-1).shape[0]
id += 1
return cov_inv.detach(), mean, {'std_id': std_id, 'std_index': std_index}
# For discrete action space
class DiscretePolicy(nn.Module):
def __init__(self, state_dim, action_num, hidden_size=(128, 128), activation='tanh'):
super().__init__()
self.is_disc_action = True
if activation == 'tanh':
self.activation = torch.tanh
elif activation == 'relu':
self.activation = torch.relu
elif activation == 'sigmoid':
self.activation = torch.sigmoid
self.affine_layers = nn.ModuleList()
last_dim = state_dim
for nh in hidden_size:
self.affine_layers.append(nn.Linear(last_dim, nh))
last_dim = nh
self.action_head = nn.Linear(last_dim, action_num)
self.action_head.weight.data.mul_(0.1)
self.action_head.bias.data.mul_(0.0)
def forward(self, x):
for affine in self.affine_layers:
x = self.activation(affine(x))
action_prob = torch.softmax(self.action_head(x), dim=1)
return action_prob
def select_action(self, x):
action_prob = self.forward(x)
action = action_prob.multinomial(1)
return action
def get_kl(self, x):
action_prob1 = self.forward(x)
action_prob0 = action_prob1.detach()
kl = action_prob0 * (torch.log(action_prob0) - torch.log(action_prob1))
return kl.sum(1, keepdim=True)
def get_log_prob(self, x, actions):
action_prob = self.forward(x)
return torch.log(action_prob.gather(1, actions.long().unsqueeze(1)))
def get_fim(self, x):
action_prob = self.forward(x)
M = action_prob.pow(-1).view(-1).detach()
return M, action_prob, {}
Value Network¶
The network $V_\phi(s)$ estimates the scalar value estimating expected return from state $s$ .
class Value(nn.Module):
def __init__(self, state_dim, hidden_size=(128, 128), activation='tanh'):
super().__init__()
if activation == 'tanh':
self.activation = torch.tanh
elif activation == 'relu':
self.activation = torch.relu
elif activation == 'sigmoid':
self.activation = torch.sigmoid
self.affine_layers = nn.ModuleList()
last_dim = state_dim
for nh in hidden_size:
self.affine_layers.append(nn.Linear(last_dim, nh))
last_dim = nh
self.value_head = nn.Linear(last_dim, 1)
self.value_head.weight.data.mul_(0.1)
self.value_head.bias.data.mul_(0.0)
def forward(self, x):
for affine in self.affine_layers:
x = self.activation(affine(x))
value = self.value_head(x)
return value
Sample Collector¶
get trajectory of samples and stored in a buffer
from collections import namedtuple
import random
Transition = namedtuple('Transition', ('state', 'action', 'mask', 'next_state',
'reward'))
class Memory(object):
def __init__(self):
self.memory = []
def push(self, *args):
"""Saves a transition."""
self.memory.append(Transition(*args))
def sample(self, batch_size=None):
if batch_size is None:
return Transition(*zip(*self.memory))
else:
random_batch = random.sample(self.memory, batch_size)
return Transition(*zip(*random_batch))
def append(self, new_memory):
self.memory += new_memory.memory
def __len__(self):
return len(self.memory)
def collect_samples(pid, queue, env, policy, custom_reward,
mean_action, render, running_state, min_batch_size):
if pid > 0:
torch.manual_seed(torch.randint(0, 5000, (1,)) * pid)
if hasattr(env, 'np_random'):
env.np_random.seed(env.np_random.randint(5000) * pid)
if hasattr(env, 'env') and hasattr(env.env, 'np_random'):
env.env.np_random.seed(env.env.np_random.randint(5000) * pid)
log = dict()
memory = Memory()
num_steps = 0
total_reward = 0
min_reward = 1e6
max_reward = -1e6
total_c_reward = 0
min_c_reward = 1e6
max_c_reward = -1e6
num_episodes = 0
while num_steps < min_batch_size:
state = env.reset()
if running_state is not None:
state = running_state(state)
reward_episode = 0
for t in range(10000):
state_var = tensor(state).unsqueeze(0)
with torch.no_grad():
# If in evaluation mode, turn off exploration by using mean action.
if mean_action:
if policy_net.is_disc_action:
# Discrete action takes the action with max probability
action_prob = policy_net(state_var).cpu().numpy()
action = np.argmax(action_prob)
else:
# Discrete action takes the mean of action distribution
action_mean, _, _ = policy_net(state_var)
action = action_mean.cpu().numpy()
else:
action = policy.select_action(state_var)[0].numpy()
reward_episode += reward
if running_state is not None:
next_state = running_state(next_state.squeeze())
if custom_reward is not None:
reward = custom_reward(state, action)
total_c_reward += reward
min_c_reward = min(min_c_reward, reward)
max_c_reward = max(max_c_reward, reward)
mask = 0 if done else 1
memory.push(state, action, mask, next_state, reward)
if render:
env.render()
if done:
break
state = next_state
# log stats
num_steps += (t + 1)
num_episodes += 1
total_reward += reward_episode
min_reward = min(min_reward, reward_episode)
max_reward = max(max_reward, reward_episode)
log['num_steps'] = num_steps
log['num_episodes'] = num_episodes
log['total_reward'] = total_reward
log['avg_reward'] = total_reward / num_episodes
log['max_reward'] = max_reward
log['min_reward'] = min_reward
if custom_reward is not None:
log['total_c_reward'] = total_c_reward
log['avg_c_reward'] = total_c_reward / num_steps
log['max_c_reward'] = max_c_reward
log['min_c_reward'] = min_c_reward
if queue is not None:
queue.put([pid, memory, log])
else:
return memory, log
def merge_log(log_list):
log = dict()
log['total_reward'] = sum([x['total_reward'] for x in log_list])
log['num_episodes'] = sum([x['num_episodes'] for x in log_list])
log['num_steps'] = sum([x['num_steps'] for x in log_list])
log['avg_reward'] = log['total_reward'] / log['num_episodes']
log['max_reward'] = max([x['max_reward'] for x in log_list])
log['min_reward'] = min([x['min_reward'] for x in log_list])
if 'total_c_reward' in log_list[0]:
log['total_c_reward'] = sum([x['total_c_reward'] for x in log_list])
log['avg_c_reward'] = log['total_c_reward'] / log['num_steps']
log['max_c_reward'] = max([x['max_c_reward'] for x in log_list])
log['min_c_reward'] = min([x['min_c_reward'] for x in log_list])
return log
Estimate Advantages¶
Measures how much better or worse the taken action $a_t$ was compared to the expected value of the state. $$\large A_t = Q(s_t,a_t) - V_\phi(s_t).$$
def estimate_advantages(rewards, masks, values, gamma, tau, device):
rewards, masks, values = to_device(torch.device('cpu'), rewards, masks, values)
tensor_type = type(rewards)
deltas = tensor_type(rewards.size(0), 1)
advantages = tensor_type(rewards.size(0), 1)
prev_value = 0
prev_advantage = 0
for i in reversed(range(rewards.size(0))):
deltas[i] = rewards[i] + gamma * prev_value * masks[i] - values[i]
advantages[i] = deltas[i] + gamma * tau * prev_advantage * masks[i]
prev_value = values[i, 0]
prev_advantage = advantages[i, 0]
returns = values + advantages
advantages = (advantages - advantages.mean()) / advantages.std()
advantages, returns = to_device(device, advantages, returns)
return advantages, returns
Conjugate Gradient¶
Given $F,g,$ the algorithm finds $x$ such that $Fx = g$ by an iterative method.
def conjugate_gradients(F_v, g, nsteps, rdotr_tol=1e-10):
# https://en.wikipedia.org/wiki/Conjugate_gradient_method
x = zeros(g.size(), device=g.device) # initialization approximation of x
r = g.clone() # residual
p = g.clone() # steepest descent direction
rdotr = torch.dot(r, r) #square of residual
for i in range(nsteps):
F_v_p = F_v(p) #compute F @ p
alpha = rdotr / torch.dot(p, F_v_p) #step size along the direction p
x += alpha * p #move x along p by step size alpha
r -= alpha * F_v_p #update the residual, g - F @ x
new_rdotr = torch.dot(r, r)
betta = new_rdotr / rdotr #conjugate gradient coefficient beta, ensures the successive directions are conjugate (orthogonal to F).
p = r + betta * p #update the search direction
rdotr = new_rdotr
if rdotr < rdotr_tol:
break
return x
Line Search¶
Finding the best scalar on a fixed direction that optimize the (surrogate) objective function.
def line_search(model, f, x, fullstep, expected_improve_full, max_backtracks=10, accept_ratio=0.1):
fval = f(True).item()
for stepfrac in [.5**x for x in range(max_backtracks)]:
# Compute new parameter for policy network
x_new = x + stepfrac * fullstep
# Update policy network with new parameter
set_flat_params_to(model, x_new)
# Compute new surrogate function value
fval_new = f(True).item()
# Compute difference between new and old surrogate function
actual_improve = fval - fval_new
# Compute difference under first-order approximation of surrogate function
expected_improve = expected_improve_full * stepfrac
# Compute the ratio between actual and expected improvement of surrogate values
ratio = actual_improve / expected_improve
# Decide whether to accept new parameter for policy network
if ratio > accept_ratio:
return True, x_new
return False, x
TRPO step¶
def trpo_step(policy_net, value_net, states, actions, returns, advantages, max_kl, damping, l2_reg, use_fim=True):
"""update critic"""
def get_value_loss(flat_params):
set_flat_params_to(value_net, tensor(flat_params))
for param in value_net.parameters():
if param.grad is not None:
param.grad.data.fill_(0)
values_pred = value_net(states)
value_loss = (values_pred - returns).pow(2).mean()
# weight decay
for param in value_net.parameters():
value_loss += param.pow(2).sum() * l2_reg
value_loss.backward()
return value_loss.item(), get_flat_grad_from(value_net.parameters()).cpu().numpy()
flat_params, _, opt_info = scipy.optimize.fmin_l_bfgs_b(get_value_loss,
get_flat_params_from(value_net).detach().cpu().numpy(),
maxiter=25)
set_flat_params_to(value_net, tensor(flat_params))
"""update policy"""
with torch.no_grad():
fixed_log_probs = policy_net.get_log_prob(states, actions)
"""define the loss function for TRPO:
loss = (-1) * Advantage*(pi_θ/pi_θ_k)"""
def get_loss(volatile=False):
with torch.set_grad_enabled(not volatile):
log_probs = policy_net.get_log_prob(states, actions)
action_loss = -advantages * torch.exp(log_probs - fixed_log_probs)
return action_loss.mean()
"""use Fisher information matrix for Hessian*vector"""
def Fvp_fim(v):
M, mu, info = policy_net.get_fim(states)
mu = mu.view(-1)
filter_input_ids = set() if policy_net.is_disc_action else set([info['std_id']])
t = ones(mu.size(), requires_grad=True, device=mu.device)
mu_t = (mu * t).sum()
Jt = compute_flat_grad(mu_t, policy_net.parameters(), filter_input_ids=filter_input_ids, create_graph=True)
Jtv = (Jt * v).sum()
Jv = torch.autograd.grad(Jtv, t)[0]
MJv = M * Jv.detach()
mu_MJv = (MJv * mu).sum()
JTMJv = compute_flat_grad(mu_MJv, policy_net.parameters(), filter_input_ids=filter_input_ids).detach()
JTMJv /= states.shape[0]
if not policy_net.is_disc_action:
std_index = info['std_index']
JTMJv[std_index: std_index + M.shape[0]] += 2 * v[std_index: std_index + M.shape[0]]
return JTMJv + v * damping
"""directly compute Hessian*vector from KL"""
def Fvp_direct(v):
# compute kl divergence between current policy and old policy
kl = policy_net.get_kl(states)
kl = kl.mean()
# First order gradient g_KL = ▽_{θ} KL
grads = torch.autograd.grad(kl, policy_net.parameters(), create_graph=True)
flat_grad_kl = torch.cat([grad.view(-1) for grad in grads])
# Inner product of g_KL and v = g_KL·v
kl_v = (flat_grad_kl * v).sum()
# gradient of g_KL·v
# = (gradient of g_KL) · v
# = Hessian matrix · v
# = H·v
grads = torch.autograd.grad(kl_v, policy_net.parameters())
flat_grad_grad_kl = torch.cat([grad.contiguous().view(-1) for grad in grads]).detach()
# Return (H + dI)v instead of Hv to present ill-conditioned H.
return flat_grad_grad_kl + v * damping
Fvp = Fvp_fim if use_fim else Fvp_direct
# Compute loss := (-1)*surrogate function
loss = get_loss()
# Compute gradient of surrogate function
grads = torch.autograd.grad(loss, policy_net.parameters())
# Flatten tensor into vector g
loss_grad = torch.cat([grad.view(-1) for grad in grads]).detach()
# conjugate gradient solve : Hv = g for v = H^(-1)g
# Compute Hv by Fvp function
# stepdir is approximately H^(-1)g
stepdir = conjugate_gradients(Fvp, -loss_grad, 10)
# denominator
# = g.T H^(-1) g
# = g.T H^(-1).T g
# = [H^(-1)g].T g
# = [H^(-1)g].T HH^(-1) g
# = [H^(-1)g].T H [H^(-1) g]
# = stepdir.T H(stepdir)
denominator = 0.5 * (stepdir.dot(Fvp(stepdir)))
coeff = math.sqrt(max_kl / denominator)
fullstep = stepdir * coeff
# Expected improve for surrogate function in first-order approximation:
# L(θ_k, θ) = g.T (θ - θ_k)
# = g.T (θ_k + step - θ_k)
# = g.T (step)
expected_improve = -loss_grad.dot(fullstep)
prev_params = get_flat_params_from(policy_net)
"""
line search for step size for satisfying the KL divergence constraint
"""
success, new_params = line_search(policy_net, get_loss, prev_params, fullstep, expected_improve)
set_flat_params_to(policy_net, new_params)
return success
Agent¶
class Agent:
def __init__(self, env, policy, device, custom_reward=None, running_state=None, num_threads=1):
self.env = env
self.policy = policy
self.device = device
self.custom_reward = custom_reward
self.running_state = running_state
self.num_threads = num_threads
def collect_samples(self, min_batch_size, mean_action=False, render=False):
t_start = time.time()
to_device(torch.device('cpu'), self.policy)
thread_batch_size = int(math.floor(min_batch_size / self.num_threads))
queue = multiprocessing.Queue()
workers = []
for i in range(self.num_threads-1):
worker_args = (i+1, queue, self.env, self.policy, self.custom_reward, mean_action,
False, self.running_state, thread_batch_size)
workers.append(multiprocessing.Process(target=collect_samples, args=worker_args))
for worker in workers:
worker.start()
memory, log = collect_samples(0, None, self.env, self.policy, self.custom_reward, mean_action,
render, self.running_state, thread_batch_size)
worker_logs = [None] * len(workers)
worker_memories = [None] * len(workers)
for _ in workers:
pid, worker_memory, worker_log = queue.get()
worker_memories[pid - 1] = worker_memory
worker_logs[pid - 1] = worker_log
for worker_memory in worker_memories:
memory.append(worker_memory)
batch = memory.sample()
if self.num_threads > 1:
log_list = [log] + worker_logs
log = merge_log(log_list)
to_device(self.device, self.policy)
t_end = time.time()
log['sample_time'] = t_end - t_start
log['action_mean'] = np.mean(np.vstack(batch.action), axis=0)
log['action_min'] = np.min(np.vstack(batch.action), axis=0)
log['action_max'] = np.max(np.vstack(batch.action), axis=0)
return batch, log
CartPole¶

Goal: Balance a pole upright on a moving cart by applying forces to the cart. The agent must prevent the pole from falling or the cart from moving out of bounds.
State (observation): continuous vector $$ s_t = [\,x_t,\; \dot{x}_t,\; \theta_t,\; \dot{\theta}_t\,] $$ where
- $x_t$: cart position (meters) — roughly in $[-2.4, 2.4]$
- $\dot{x}_t$: cart velocity (m/s)
- $\theta_t$: pole angle from vertical (radians, $0$ = upright, $\approx [-12^\circ, 12^\circ]$)
- $\dot{\theta}_t$: pole angular velocity (rad/s)
Actions: discrete set $$ a_t \in \{\,0,\,1\,\} $$
- 0: push cart to the left
- 1: push cart to the right
Reward: scalar feedback each step $$ r_t = \begin{cases} 1, & \text{if pole remains upright and within bounds}\\[4pt] 0, & \text{otherwise (episode ends)} \end{cases} $$
Episode termination conditions:
- $|\theta_t| > 12^\circ$ (pole falls)
- $|x_t| > 2.4$ (cart out of range)
- episode length reaches 200 steps (success)
Training part¶
import argparse
args = parser.parse_args(args=[
'--env-name', 'CartPole-v0',
'--render',
'--log-std', '-0.0',
'--gamma', '0.99',
'--tau', '0.95',
'--l2-reg', '1e-3',
'--max-kl', '1e-2',
'--damping', '1e-2',
'--num-threads', '8',
'--seed', '1',
'--min-batch-size', '2048',
'--eval-batch-size', '2048',
'--max-iter-num', '50',
'--log-interval', '1',
'--save-model-interval', '0',
'--gpu-index', '0'
])
# Printing some of the parsed arguments for demonstration
print("Environment Name:", args.env_name)
print("Model Path:", args.model_path)
print("Render Environment:", args.render, type(args.render))
print("Tau:", args.tau, type(args.tau))
print("GPU Index:", args.gpu_index, type(args.gpu_index))
dtype = torch.float64
torch.set_default_dtype(dtype)
device = torch.device('cuda', index=args.gpu_index) if torch.cuda.is_available() else torch.device('cpu')
if torch.cuda.is_available():
torch.cuda.set_device(args.gpu_index)
"""environment"""
env = gym.make(args.env_name)
state_dim = env.observation_space.shape[0]
is_disc_action = len(env.action_space.shape) == 0
running_state = ZFilter((state_dim,), clip=5)
# running_reward = ZFilter((1,), demean=False, clip=10)
"""seeding"""
np.random.seed(args.seed)
torch.manual_seed(args.seed)
env.seed(args.seed)
"""define actor and critic"""
if args.model_path is None:
if is_disc_action:
policy_net = DiscretePolicy(state_dim, env.action_space.n)
else:
policy_net = Policy(state_dim, env.action_space.shape[0], log_std=args.log_std)
value_net = Value(state_dim)
else:
policy_net, value_net, running_state = pickle.load(open(args.model_path, "rb"))
policy_net.to(device)
value_net.to(device)
"""create agent"""
agent = Agent(env, policy_net, device, running_state=running_state, num_threads=args.num_threads)
def update_params(batch):
states = torch.from_numpy(np.stack(batch.state)).to(dtype).to(device)
actions = torch.from_numpy(np.stack(batch.action)).to(dtype).to(device)
rewards = torch.from_numpy(np.stack(batch.reward)).to(dtype).to(device)
masks = torch.from_numpy(np.stack(batch.mask)).to(dtype).to(device)
with torch.no_grad():
values = value_net(states)
"""get advantage estimation from the trajectories"""
advantages, returns = estimate_advantages(rewards, masks, values, args.gamma, args.tau, device)
"""perform TRPO update"""
trpo_step(policy_net, value_net, states, actions, returns, advantages, args.max_kl, args.damping, args.l2_reg)
def main_train():
best_avg_reward = float('-inf')
average_train_rewards = []
for i_iter in range(args.max_iter_num):
"""generate multiple trajectories that reach the minimum batch_size"""
batch, log = agent.collect_samples(args.min_batch_size, render=args.render)
t0 = time.time()
update_params(batch)
t1 = time.time()
"""evaluate with determinstic action (remove noise for exploration)"""
_, log_eval = agent.collect_samples(args.eval_batch_size, mean_action=True)
t2 = time.time()
average_train_rewards.append(log['avg_reward'])
if i_iter % args.log_interval == 0:
print('{}\tT_sample {:.4f}\tT_update {:.4f}\tT_eval {:.4f}\ttrain_R_min {:.2f}\ttrain_R_max {:.2f}\ttrain_R_avg {:.2f}\teval_R_avg {:.2f}'.format(
i_iter, log['sample_time'], t1-t0, t2-t1, log['min_reward'], log['max_reward'], log['avg_reward'], log_eval['avg_reward']))
# Save best model
if log['avg_reward'] > best_avg_reward:
best_avg_reward = log['avg_reward']
to_device(torch.device('cpu'), policy_net, value_net)
check_path('learned_models')
pickle.dump((policy_net, value_net, running_state),
open(os.path.join('learned_models/{}_trpo.p'.format(args.env_name)), 'wb'))
print(f'New best average reward={best_avg_reward}. Model saved!')
to_device(device, policy_net, value_net)
"""clean up gpu memory"""
torch.cuda.empty_cache()
plt.plot(average_train_rewards)
plt.xlabel('Iteration')
plt.ylabel('Average Training Reward')
plt.show()
Environment Name: CartPole-v0 Model Path: None Render Environment: True <class 'bool'> Tau: 0.95 <class 'float'> GPU Index: 0 <class 'int'>
/usr/local/lib/python3.10/dist-packages/gym/envs/registration.py:593: UserWarning: WARN: The environment CartPole-v0 is out of date. You should consider upgrading to version `v1`.
logger.warn(
main_train()
/usr/local/lib/python3.10/dist-packages/ipykernel/ipkernel.py:283: DeprecationWarning: `should_run_async` will not call `transform_cell` automatically in the future. Please pass the result to `transformed_cell` argument and any exception that happen during thetransform in `preprocessing_exc_tuple` in IPython 7.17 and above. and should_run_async(code) /usr/lib/python3.10/multiprocessing/popen_fork.py:66: RuntimeWarning: os.fork() was called. os.fork() is incompatible with multithreaded code, and JAX is multithreaded, so this will likely lead to a deadlock. self.pid = os.fork() <ipython-input-78-b6fb2253d08f>:33: DeprecationWarning: Conversion of an array with ndim > 0 to a scalar is deprecated, and will error in future. Ensure you extract a single element from your array before performing this operation. (Deprecated NumPy 1.25.) action = int(action) if policy.is_disc_action else action.astype(np.float64) <ipython-input-78-b6fb2253d08f>:33: DeprecationWarning: Conversion of an array with ndim > 0 to a scalar is deprecated, and will error in future. Ensure you extract a single element from your array before performing this operation. (Deprecated NumPy 1.25.) action = int(action) if policy.is_disc_action else action.astype(np.float64) <ipython-input-78-b6fb2253d08f>:33: DeprecationWarning: Conversion of an array with ndim > 0 to a scalar is deprecated, and will error in future. Ensure you extract a single element from your array before performing this operation. (Deprecated NumPy 1.25.) action = int(action) if policy.is_disc_action else action.astype(np.float64) <ipython-input-78-b6fb2253d08f>:33: DeprecationWarning: Conversion of an array with ndim > 0 to a scalar is deprecated, and will error in future. Ensure you extract a single element from your array before performing this operation. (Deprecated NumPy 1.25.) action = int(action) if policy.is_disc_action else action.astype(np.float64) <ipython-input-78-b6fb2253d08f>:33: DeprecationWarning: Conversion of an array with ndim > 0 to a scalar is deprecated, and will error in future. Ensure you extract a single element from your array before performing this operation. (Deprecated NumPy 1.25.) action = int(action) if policy.is_disc_action else action.astype(np.float64) <ipython-input-78-b6fb2253d08f>:33: DeprecationWarning: Conversion of an array with ndim > 0 to a scalar is deprecated, and will error in future. Ensure you extract a single element from your array before performing this operation. (Deprecated NumPy 1.25.) action = int(action) if policy.is_disc_action else action.astype(np.float64) <ipython-input-78-b6fb2253d08f>:33: DeprecationWarning: Conversion of an array with ndim > 0 to a scalar is deprecated, and will error in future. Ensure you extract a single element from your array before performing this operation. (Deprecated NumPy 1.25.) action = int(action) if policy.is_disc_action else action.astype(np.float64) <ipython-input-78-b6fb2253d08f>:33: DeprecationWarning: Conversion of an array with ndim > 0 to a scalar is deprecated, and will error in future. Ensure you extract a single element from your array before performing this operation. (Deprecated NumPy 1.25.) action = int(action) if policy.is_disc_action else action.astype(np.float64)
0 T_sample 6.9662 T_update 2.2001 T_eval 1.3505 train_R_min 10.00 train_R_max 48.00 train_R_avg 20.58 eval_R_avg 9.32 New best average reward=20.58252427184466. Model saved! 1 T_sample 6.1537 T_update 1.4174 T_eval 0.8339 train_R_min 9.00 train_R_max 69.00 train_R_avg 24.26 eval_R_avg 9.36 New best average reward=24.255555555555556. Model saved! 2 T_sample 6.5259 T_update 2.3797 T_eval 1.3120 train_R_min 10.00 train_R_max 108.00 train_R_avg 31.69 eval_R_avg 9.43 New best average reward=31.690140845070424. Model saved! 3 T_sample 6.8312 T_update 1.3727 T_eval 0.8257 train_R_min 11.00 train_R_max 137.00 train_R_avg 49.64 eval_R_avg 9.30 New best average reward=49.644444444444446. Model saved! 4 T_sample 8.4459 T_update 1.7972 T_eval 0.8226 train_R_min 17.00 train_R_max 200.00 train_R_avg 103.35 eval_R_avg 9.44 New best average reward=103.34615384615384. Model saved! 5 T_sample 7.9421 T_update 1.9472 T_eval 0.8011 train_R_min 39.00 train_R_max 200.00 train_R_avg 156.00 eval_R_avg 9.33 New best average reward=156.0. Model saved! 6 T_sample 8.1033 T_update 2.8892 T_eval 1.3873 train_R_min 61.00 train_R_max 200.00 train_R_avg 182.50 eval_R_avg 9.28 New best average reward=182.5. Model saved! 7 T_sample 8.7392 T_update 2.3456 T_eval 1.3718 train_R_min 200.00 train_R_max 200.00 train_R_avg 200.00 eval_R_avg 9.37 New best average reward=200.0. Model saved! 8 T_sample 9.2268 T_update 2.0117 T_eval 0.8387 train_R_min 200.00 train_R_max 200.00 train_R_avg 200.00 eval_R_avg 9.32 9 T_sample 8.6555 T_update 2.3009 T_eval 0.8485 train_R_min 200.00 train_R_max 200.00 train_R_avg 200.00 eval_R_avg 9.27 10 T_sample 8.5708 T_update 2.1332 T_eval 0.8342 train_R_min 106.00 train_R_max 200.00 train_R_avg 188.81 eval_R_avg 9.43 11 T_sample 8.8555 T_update 3.1993 T_eval 1.0734 train_R_min 186.00 train_R_max 200.00 train_R_avg 199.06 eval_R_avg 9.39 12 T_sample 6.5218 T_update 1.6870 T_eval 0.8553 train_R_min 89.00 train_R_max 200.00 train_R_avg 164.24 eval_R_avg 9.25 13 T_sample 7.6392 T_update 1.8031 T_eval 0.8556 train_R_min 141.00 train_R_max 200.00 train_R_avg 185.25 eval_R_avg 9.36 14 T_sample 8.2042 T_update 1.9857 T_eval 0.7963 train_R_min 128.00 train_R_max 200.00 train_R_avg 189.56 eval_R_avg 9.27 15 T_sample 8.6218 T_update 3.1624 T_eval 1.0995 train_R_min 165.00 train_R_max 200.00 train_R_avg 190.62 eval_R_avg 9.34 16 T_sample 8.5938 T_update 2.4173 T_eval 1.2654 train_R_min 175.00 train_R_max 200.00 train_R_avg 197.25 eval_R_avg 9.33 17 T_sample 9.1760 T_update 1.9041 T_eval 0.8320 train_R_min 200.00 train_R_max 200.00 train_R_avg 200.00 eval_R_avg 9.33 18 T_sample 8.6765 T_update 2.0318 T_eval 0.8679 train_R_min 200.00 train_R_max 200.00 train_R_avg 200.00 eval_R_avg 9.40 19 T_sample 8.6492 T_update 2.3782 T_eval 0.8210 train_R_min 196.00 train_R_max 200.00 train_R_avg 199.75 eval_R_avg 9.30 20 T_sample 8.5835 T_update 3.2389 T_eval 0.8889 train_R_min 200.00 train_R_max 200.00 train_R_avg 200.00 eval_R_avg 9.37 21 T_sample 8.5648 T_update 2.4408 T_eval 1.4179 train_R_min 194.00 train_R_max 200.00 train_R_avg 199.62 eval_R_avg 9.31 22 T_sample 9.1937 T_update 1.9866 T_eval 0.8288 train_R_min 175.00 train_R_max 200.00 train_R_avg 198.06 eval_R_avg 9.43 23 T_sample 8.5149 T_update 1.9800 T_eval 0.8274 train_R_min 188.00 train_R_max 200.00 train_R_avg 199.25 eval_R_avg 9.35 24 T_sample 7.5512 T_update 3.0359 T_eval 0.8059 train_R_min 147.00 train_R_max 200.00 train_R_avg 196.69 eval_R_avg 9.26 25 T_sample 8.6505 T_update 3.2440 T_eval 1.4094 train_R_min 200.00 train_R_max 200.00 train_R_avg 200.00 eval_R_avg 9.36 26 T_sample 8.9337 T_update 2.0373 T_eval 1.2876 train_R_min 180.00 train_R_max 200.00 train_R_avg 198.75 eval_R_avg 9.46 27 T_sample 8.5673 T_update 1.9234 T_eval 0.8319 train_R_min 168.00 train_R_max 200.00 train_R_avg 198.00 eval_R_avg 9.35 28 T_sample 8.6830 T_update 1.9177 T_eval 0.8250 train_R_min 185.00 train_R_max 200.00 train_R_avg 199.06 eval_R_avg 9.46 29 T_sample 9.1688 T_update 3.0141 T_eval 0.7912 train_R_min 200.00 train_R_max 200.00 train_R_avg 200.00 eval_R_avg 9.39 30 T_sample 8.6999 T_update 3.1842 T_eval 1.3058 train_R_min 200.00 train_R_max 200.00 train_R_avg 200.00 eval_R_avg 9.32 31 T_sample 8.9348 T_update 2.0933 T_eval 1.4009 train_R_min 200.00 train_R_max 200.00 train_R_avg 200.00 eval_R_avg 9.31 32 T_sample 9.1993 T_update 1.9717 T_eval 0.8208 train_R_min 200.00 train_R_max 200.00 train_R_avg 200.00 eval_R_avg 9.38 33 T_sample 8.6733 T_update 1.9985 T_eval 0.8808 train_R_min 200.00 train_R_max 200.00 train_R_avg 200.00 eval_R_avg 9.27 34 T_sample 8.8057 T_update 2.2194 T_eval 0.8290 train_R_min 200.00 train_R_max 200.00 train_R_avg 200.00 eval_R_avg 9.37 35 T_sample 8.7667 T_update 3.3979 T_eval 0.8106 train_R_min 200.00 train_R_max 200.00 train_R_avg 200.00 eval_R_avg 9.39 36 T_sample 8.6001 T_update 2.8181 T_eval 1.4626 train_R_min 200.00 train_R_max 200.00 train_R_avg 200.00 eval_R_avg 9.35 37 T_sample 9.1161 T_update 2.0132 T_eval 1.1998 train_R_min 200.00 train_R_max 200.00 train_R_avg 200.00 eval_R_avg 9.35 38 T_sample 8.6077 T_update 2.0789 T_eval 0.9709 train_R_min 200.00 train_R_max 200.00 train_R_avg 200.00 eval_R_avg 9.50 39 T_sample 8.7456 T_update 2.1392 T_eval 0.8350 train_R_min 200.00 train_R_max 200.00 train_R_avg 200.00 eval_R_avg 9.45 40 T_sample 8.5873 T_update 3.0868 T_eval 1.0289 train_R_min 200.00 train_R_max 200.00 train_R_avg 200.00 eval_R_avg 9.31 41 T_sample 8.5901 T_update 2.3798 T_eval 1.3293 train_R_min 200.00 train_R_max 200.00 train_R_avg 200.00 eval_R_avg 9.38 42 T_sample 9.1466 T_update 1.9696 T_eval 0.8410 train_R_min 199.00 train_R_max 200.00 train_R_avg 199.94 eval_R_avg 9.37 43 T_sample 8.6570 T_update 2.1485 T_eval 0.9844 train_R_min 200.00 train_R_max 200.00 train_R_avg 200.00 eval_R_avg 9.43 44 T_sample 8.5729 T_update 2.1064 T_eval 0.8200 train_R_min 200.00 train_R_max 200.00 train_R_avg 200.00 eval_R_avg 9.27 45 T_sample 7.9804 T_update 3.0877 T_eval 1.1612 train_R_min 154.00 train_R_max 200.00 train_R_avg 195.12 eval_R_avg 9.36 46 T_sample 8.6089 T_update 2.4265 T_eval 1.3200 train_R_min 200.00 train_R_max 200.00 train_R_avg 200.00 eval_R_avg 9.32 47 T_sample 9.4919 T_update 1.9056 T_eval 0.8457 train_R_min 132.00 train_R_max 200.00 train_R_avg 192.75 eval_R_avg 9.33 48 T_sample 8.6345 T_update 2.0385 T_eval 0.8841 train_R_min 176.00 train_R_max 200.00 train_R_avg 198.50 eval_R_avg 9.32 49 T_sample 7.1949 T_update 3.0322 T_eval 0.8242 train_R_min 77.00 train_R_max 200.00 train_R_avg 187.81 eval_R_avg 9.33
Evaluation part¶
import argparse
parser = argparse.ArgumentParser(description='PyTorch TRPO example')
parser.add_argument('--env-name', default="Hopper-v2", metavar='G',
help='name of the environment to run')
parser.add_argument('--model-path', metavar='G', required=True,
help='path of pre-trained model')
parser.add_argument('--render', action='store_true', default=False,
help='render the environment')
parser.add_argument('--seed', type=int, default=1, metavar='N',
help='random seed (default: 1)')
parser.add_argument('--gpu-index', type=int, default=0, metavar='N')
parser.add_argument('--num-eval', type=int, default=1, metavar='N')
args = parser.parse_args(args=[
'--env-name', 'CartPole-v0',
'--model-path', 'learned_models/CartPole-v0_trpo.p',
'--seed', '1',
'--gpu-index', '0',
'--num-eval', '10'
])
dtype = torch.float64
torch.set_default_dtype(dtype)
device = torch.device('cuda', index=args.gpu_index) if torch.cuda.is_available() else torch.device('cpu')
if torch.cuda.is_available():
torch.cuda.set_device(args.gpu_index)
"""environment"""
env = gym.make(args.env_name)
state_dim = env.observation_space.shape[0]
is_disc_action = len(env.action_space.shape) == 0
running_state = ZFilter((state_dim,), clip=5)
"""seeding"""
np.random.seed(args.seed)
torch.manual_seed(args.seed)
env.seed(args.seed)
"""define actor and critic"""
policy_net, value_net, running_state = pickle.load(open(args.model_path, "rb"))
policy_net.to(device)
value_net.to(device)
"""create agent"""
agent = Agent(env, policy_net, device, running_state=running_state, num_threads=1)
mean_action = True # In evaluation, there is no exploration of action, just use mean action.
def main_eval():
episode_rewards = []
for e in range(1, args.num_eval+1):
done = False
state = env.reset()
if running_state is not None:
state = running_state(state.squeeze())
reward_episode = 0
while not done:
state_var = tensor(state, dtype=dtype).unsqueeze(0).to(device)
with torch.no_grad():
if policy_net.is_disc_action:
# Discrete action takes the action with max probability
action_prob = policy_net(state_var).cpu().numpy()
action = np.argmax(action_prob)
else:
# Discrete action takes the mean of action distribution
action_mean, _, _ = policy_net(state_var)
action = action_mean.cpu().numpy()
next_state, reward, done, _ = env.step(action)
if running_state is not None:
next_state = running_state(next_state.squeeze())
state = next_state
if args.render:
env.render()
reward_episode += reward
print(f"Episode {e} Total Reward {reward_episode}")
episode_rewards.append(reward_episode)
"""clean up gpu memory"""
torch.cuda.empty_cache()
env.close()
print(f"Number of Episodes {args.num_eval} Mean Reward {np.mean(episode_rewards)} Std Reward {np.std(episode_rewards)}")
return episode_rewards
main_eval()
/usr/local/lib/python3.10/dist-packages/gym/envs/registration.py:593: UserWarning: WARN: The environment CartPole-v0 is out of date. You should consider upgrading to version `v1`.
logger.warn(
Episode 1 Total Reward 200.0 Episode 2 Total Reward 200.0 Episode 3 Total Reward 200.0 Episode 4 Total Reward 200.0 Episode 5 Total Reward 200.0 Episode 6 Total Reward 200.0 Episode 7 Total Reward 200.0 Episode 8 Total Reward 200.0 Episode 9 Total Reward 200.0 Episode 10 Total Reward 200.0 Number of Episodes 10 Mean Reward 200.0 Std Reward 0.0
[200.0, 200.0, 200.0, 200.0, 200.0, 200.0, 200.0, 200.0, 200.0, 200.0]
Conclusion¶
Trust Region Policy Optimization (TRPO) improves the stability of policy gradient methods by limiting how far the policy is allowed to move. The core idea is to solve the following constrained optimization problem:
$$\large \max_\theta \; L(\theta) \quad \text{s.t.} \quad D_\mathrm{KL}\!\left(\pi_{\theta_{\text{old}}} \,\|\, \pi_\theta\right) \le \delta. $$
This trust region prevents overly large policy updates and leads to more consistent learning progress.
Key ideas
- Trust region: restrict policy change using a KL-divergence constraint
- Surrogate objective: optimize a first-order approximation to expected return
- Natural gradient: optimal direction becomes (F^{-1} g)
- Conjugate gradient: compute the natural gradient without inverting (F)
- Line search: ensure the final update satisfies the KL limit
TRPO provides small but reliable policy improvements and is more stable than vanilla policy gradient, forming the basis for later methods like PPO.